package com.springboot.common.exception;


import com.springboot.common.constant.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Optional;

/**
 * 自定义业务异常类
 */
public class BusinessException extends RuntimeException {

    private Logger logger = LoggerFactory.getLogger(BusinessException.class);

    // 错误码
    private String errorCode = ErrorCode.SUCCESS.getCode();

    //错误信息
    private String errorMsg = "";

    //错误信息对应的参数，String.format(errorMsg, params); --> String.format("%s 是未授权用户，禁止登陆", "yaoym");
    private String[] params;
/*
    public BusinessException(String errorCode) {
        this.errorCode = errorCode;
        this.errorMsg = "";
        logger.error("系统遇到如下异常，异常码：{}>>>异常信息：{}", errorCode, errorMsg);
    }
*/

    public BusinessException(Enum error) {
        this.errorCode = error.name();
        this.errorMsg =  this.getMessage(error);
        logger.info("系统遇到如下异常，异常码：{}>>>异常信息：{}", errorCode, errorMsg);
    }

    public BusinessException(Enum error, String errorMsg) {
        this.errorCode = error.name();
        this.errorMsg =  errorMsg;
        logger.info("系统遇到如下异常，异常码：{}>>>异常信息：{}", errorCode, errorMsg);
    }

    private String getMessage(Enum error){
        Field field = ReflectionUtils.findField(error.getClass(), "message");
        ReflectionUtils.makeAccessible(field);
        return Optional.ofNullable(ReflectionUtils.getField(field, error)).orElse("").toString();
    }


    public static void main(String[] args) {
        BusinessException businessException = new BusinessException(ErrorCode.SUCCESS);
        System.out.println(businessException.errorCode);
        System.out.println(businessException.errorMsg);
    }
}
